//
//  ReadDetialViewController.m
//  A Cup
//
//  Created by dllo on 15/4/22.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "ReadDetialViewController.h"
#import "MJRefresh.h"
#import "ArticleViewController.h"
#import "dataBaseHandle.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface ReadDetialViewController ()
@property(nonatomic, retain)NSMutableArray *readArr;
@property(nonatomic, retain)NSMutableArray *reArr;
@property(nonatomic, retain)UITableView *readtable ;
@property(nonatomic, retain)UITableView *retable;
@property(nonatomic, assign)NSInteger page;
@property(nonatomic, assign)NSInteger number;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, assign)UIActivityIndicatorView *activity;
@end

@implementation ReadDetialViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
         self.readArr = [NSMutableArray array];
         self.reArr = [NSMutableArray array];
        self.flag = 6;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = _titName;
    [self creatview1];
    [self creatview2];
    [self method1];
    [self method2];
    [self setSegCon];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(turnBack)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Top" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.8 * WIDTH, 0.7 * HEIGHT - 10, 36, 36);
    button.layer.borderWidth = 1;
    button.backgroundColor = [UIColor blackColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.clipsToBounds = YES;
    button.alpha = 0.8;
    button.layer.cornerRadius = 18;
    [button addTarget:self action:@selector(moveToTop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    self.activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(WIDTH/2, 100, 30, 30)];
    [self.activity setCenter:CGPointMake(self.view.frame.size.width / 2, (self.view.frame.size.height - 113) / 2)]; // 指定进度轮中心点
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activity];
    [self.view bringSubviewToFront:self.activity];
    [self.activity startAnimating];
    [_activity release];
    
}

- (void)moveToTop
{
    if (self.flag == 0) {
        self.readtable.contentOffset = CGPointMake(0, 0);
    }else{
        self.retable.contentOffset = CGPointMake(0, 0);
    }
}

- (void)turnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

//创建一个SegmentedControl 分类为最新和最热
- (void)setSegCon
{
    UISegmentedControl *segCon = [[UISegmentedControl alloc] initWithItems:@[@"最新",@"最热"]];
    segCon.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
    [segCon addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    segCon.selectedSegmentIndex = 0;
    self.flag = 0;
    segCon.tintColor = [UIColor grayColor];
    [self.view addSubview:segCon];
    [segCon release];
}

- (void)click:(id)sender
{
    UISegmentedControl *seg = (UISegmentedControl *)sender;
    NSInteger  index = seg.selectedSegmentIndex;
    switch (index) {
        case 0:
            self.readtable.hidden = NO;
            self.retable.hidden = YES;
            self.flag = 0;
            break;
        case 1 :
            self.readtable.hidden = YES;
            self.retable.hidden = NO;
            self.flag = 1;
            break;
    }
}

//解析"最新"数据
- (void)postdata1
{
    if ([dataBaseHandle shareDB].state == 1) {
        //每页刷新数据的个数
        NSString *i = [NSString stringWithFormat:@"%ld",self.page*10];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"deviceid",self.typenumber,@"typeid",@"1",@"client",@"addtime",@"sort",@"10",@"limit",@"3.0.1",@"version",@"",@"auth",i,@"start", nil];
        [manager POST:@"http://api2.pianke.me/read/columns_detail" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableDictionary *dic = responseObject;
            NSMutableDictionary *Dic = dic[@"data"];
            NSMutableArray *arr = Dic[@"list"];
            for (NSMutableDictionary *temp in arr) {
                Read *read = [[Read alloc] init];
                [read setValuesForKeysWithDictionary:temp];
                [self.readArr addObject:read];
            }
            [self.readtable reloadData];
            [self.readtable.legendFooter endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
        self.page++;
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

//解析最热数据
- (void)postdata2
{
    if ([dataBaseHandle shareDB].state == 1) {
        NSString *i = [NSString stringWithFormat:@"%ld",self.number*10];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"deviceid",self.typenumber,@"typeid",@"1",@"client",@"hot",@"sort",@"10",@"limit",@"3.0.1",@"version",@"",@"auth",i,@"start", nil];
        [manager POST:@"http://api2.pianke.me/read/columns_detail" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableDictionary *dic = responseObject;
            NSMutableDictionary *Dic = dic[@"data"];
            NSMutableArray *arr = Dic[@"list"];
            for (NSMutableDictionary *temp in arr) {
                Read *read = [[Read alloc] init];
                [read setValuesForKeysWithDictionary:temp];
                [self.reArr addObject:read];
            }
            [self.retable reloadData];
            [self.retable.legendFooter endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
        self.number++;
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

//tableview最热页面
- (void)creatview1
{
    self.readtable = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height-49-64)];
    [self.view addSubview:self.readtable];
    self.readtable.rowHeight = 120;
    [_readtable release];
    [self postdata1];
    self.readtable.hidden = NO;
    self.readtable.delegate = self;
    self.readtable.dataSource =self;
}

//tableview最新页面
- (void)creatview2
{
    self.retable = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height-49-64)];
    [self.view addSubview:self.retable];
    self.retable.rowHeight = 120;
    [_retable release];
    [self postdata2];
    self.retable.hidden = YES;
    self.retable.delegate = self;
    self.retable.dataSource =self;
}

//下拉刷新,上拉加载
- (void)method1
{
    [self.readtable addLegendFooterWithRefreshingBlock:^{
        [self postdata1];
    }];
}

- (void)method2
{
    [self.retable addLegendFooterWithRefreshingBlock:^{
        [self postdata2];
        [self.retable reloadData];
        [self.retable.footer endRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.readtable) {
        if (self.readArr.count > 0) {
            [self.activity stopAnimating];
        }
        return self.readArr.count;
    }
    return self.reArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    ReadDetialCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[ReadDetialCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
    }
    
    if (tableView == self.readtable) {
        cell.titleLabel.text = [self.readArr[indexPath.row] title];
        NSURL *url = [NSURL URLWithString:[self.readArr[indexPath.row]coverimg]];
        [cell.readimage sd_setImageWithURL:url];
        cell.contentLabel.text = [self.readArr[indexPath.row]content];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//点击cell不变色
        return cell;
    }else{
        cell.titleLabel.text = [self.reArr[indexPath.row] title];
        NSURL *url = [NSURL URLWithString:[self.reArr[indexPath.row]coverimg]];
        [cell.readimage sd_setImageWithURL:url];
        cell.contentLabel.text = [self.reArr[indexPath.row]content];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//点击cell不变色
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleViewController *articleVC = [[ArticleViewController alloc] init];
    if (tableView == self.readtable) {
        articleVC.conid = [self.readArr[indexPath.row] id];
        articleVC.reMo = self.readArr[indexPath.row];
        articleVC.sharename = [self.readArr[indexPath.row] title];
        articleVC.picUrl = [self.readArr[indexPath.row] coverimg];
       
    }else{
        articleVC.conid = [self.reArr[indexPath.row] id];
        articleVC.reMo = self.reArr[indexPath.row];
        articleVC.sharename = [self.reArr[indexPath.row] title];
        articleVC.picUrl = [self.reArr[indexPath.row] coverimg];
    }
    [self.navigationController pushViewController:articleVC animated:YES];
}

- (void)dealloc
{
    [self.readArr release];
    [self.reArr release];
    [self.readtable release];
    [self.retable release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
